﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace UnionnetClient.Model
{
	public class SettingsHelper
	{
		public event EventHandler SettingsChanged;

		public SettingsHelper()
		{
			if (File.Exists(filePath))
			{
				//反序列化设置类
				using (FileStream fs = new FileStream(filePath, FileMode.Open))
				{
					BinaryFormatter bf = new BinaryFormatter();
					settings = (Dictionary<string, object>)bf.Deserialize(fs);
				}
			}
		}

		///// <summary>
		///// 设置存放的路径
		///// </summary>
		//public string FilePath
		//{
		//    get { return filePath; }
		//    set { filePath = value; }
		//}

		//private SettingsHelper()
		//{
		//    Debug.WriteLine("[APP][INFO] Setings are stored in " + filePath);
		//}

		public virtual object this[string key]
		{
			get
			{
				object value;
				return settings.TryGetValue(key, out value) ? value : null;
			}

			set
			{
				if (settings.ContainsKey(key))
				{
					settings[key] = value;
				}
				else
				{
					settings.Add(key, value);
				}
			}
		}

		//[Conditional("REMOVE")] //待移除的方法
		//private void AddSettingsAndRemoveOriginal(params object[] keyValue)
		//{
		//    settings.Clear();
		//    for (int i = 0; i < keyValue.Length; i += 2)
		//    {
		//        settings.Add((string)keyValue[i], keyValue[i + 1]);
		//    }
		//}

		public void Save()
		{
			using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
			{
				BinaryFormatter bf = new BinaryFormatter();
				bf.Serialize(fs, settings);
			}
			OnSettingsChanged();
		}

		private readonly string COMPLETED = "__COMPLETED__";
		internal bool IsCompleted
		{
			get { return settings.ContainsKey(COMPLETED) ? (bool)settings[COMPLETED] : false; }
			set { settings[COMPLETED] = value; }
		}

		#region private
		static private string filePath = Path.Combine(AppEnvironment.AppDataFolder, "settings.b");	
		
		private void OnSettingsChanged()
		{
			if (SettingsChanged != null)
			{
				SettingsChanged(this, EventArgs.Empty);
			}
		}
		#endregion

		//#region protected
		//static protected SettingsHelper m_settings;
		//#endregion
		protected Dictionary<string, object> settings; // = new Dictionary<string, object>();
	}
}
